package com.blaze.framework.core.cloud.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.blaze.framework.core.util.constants.Constants;
import com.blaze.framework.core.util.domain.R;
import com.blaze.framework.core.util.json.JsonUtil;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.blaze.framework.core.util.domain.exception.DefaultErrorCode.LIMITING_ERROR;

/**
 * 触发限流后的异常处理
 * @author created by Zhou Zongbo on 2025/5/23.
 */
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        // Return 429 (Too Many Requests) by default.
        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        response.setCharacterEncoding(Constants.UTF_8);
        response.setContentType(Constants.CONTENT_TYPE_JSON);
        R<Object> result = R.fail(LIMITING_ERROR.getCode(), LIMITING_ERROR.getMsg());
        try (PrintWriter out = response.getWriter()) {
            out.write(JsonUtil.toJsonString(result));
            out.flush();
        }
    }
}
